rm(list = ls())

wd <- ".../Replication/"
setwd(wd)


# Load/install packages --
if (!require("pacman")) install.packages("pacman")
pacman::p_load(
  foreign, 
  ggplot2, 
  estimatr,
  texreg,
  xtable,
  fastDummies,
  sandwich,
  dplyr,
  janitor, 
  gridExtra,
  gsheet,
  zoo,
  interflex,
  lubridate,
  tidyverse,
  stringi,
  readxl,
  ri2,
  modelsummary,
  ggpubr
)

options(scipen=999)


# load database
data_police<-read.csv("Data/full police records 1827-1830.csv")

# clean
data_police$date_month <- as.Date(data_police$date_month)
data_police$date_month <- format(data_police$date_month, "%m-%d")
data_police$nro_presos[is.na(data_police$nro_presos)] <- 0
data_police$nro_presos_esclavos[is.na(data_police$nro_presos_esclavos)] <- 0
data_police$nro_presos_negroslibres[is.na(data_police$nro_presos_negroslibres)] <- 0
data_police$nro_presos_negros <- data_police$nro_presos_negroslibres + data_police$nro_presos_esclavos

# keep only entries with info on imprisoned
data_police <-  data_police %>% filter(preso==1)

# plot
dataplot <- data_police %>% 
  dplyr::group_by(date_month) %>% 
  dplyr::summarise(
    `As Share of All Imprisoned` = sum(nro_presos_negroslibres) / sum(nro_presos),
    `As Share of Blacks Imprisoned` = sum(nro_presos_negroslibres) / sum(nro_presos_negros)
  )  %>%
  pivot_longer(cols = `As Share of All Imprisoned`:`As Share of Blacks Imprisoned`,
               names_to = "variable",
               values_to = "Share")

dataplot$`Harvest Season` <- ifelse(dataplot$date_month %in% c("01-01", "02-01", "12-01"), 
                                    "Yes", "No")
Figure_4<-ggplot(data = dataplot, 
                 aes(x=date_month, y = Share, fill = `Harvest Season`)) + 
  facet_wrap(~variable, scales = "free_y") + 
  geom_col() + 
  scale_fill_grey(start = 0, end = .5) +
  scale_x_discrete(labels = c("Jan", "Feb", "Mar", "Apr",
                              "May", "Jun", "Jul", "Aug",
                              "Sep", "Oct", "Nov", "Dec")) +
  labs(x = "Month") +
  theme_minimal() + 
  theme(legend.position = "bottom",
        strip.text = element_text(size = 12))


# save
pdf("Output/Figure4.pdf",height=5, width=10)
Figure_4
dev.off()

Figure_4
